/* 
 *	Copyright (C) 2007 cooleyes
 *	eyes.cooleyes@gmail.com 
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *   
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *   
 *  You should have received a copy of the GNU General Public License
 *  along with GNU Make; see the file COPYING.  If not, write to
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 
 *  http://www.gnu.org/copyleft/gpl.html
 *
 */
 
#include "at3_parser.h"
#include "common/mem64.h"
#include <string.h>

At3Parser::At3Parser() {
	initialize();
};

At3Parser::~At3Parser() {
	close();
};

void At3Parser::initialize() {
	is_open = false;
	
	total_samples = 0;
	total_frames = 0;
	
	frame_index = 0;
	reader = 0;
	output_buffer = 0;
	read_buffer = 0;
	
	codec = 0;
	codec_initialize = false;
	
	memset(&init_data, 0, sizeof(AudioCodecInitData));
};

void At3Parser::finalize() {
	if ( reader ) {
		buffered_reader_close(reader);
	}
	if ( frame_index ) {
		free(frame_index);
	}
	if ( output_buffer ) {
		free(output_buffer);
	}
	if ( read_buffer ) {
		free(read_buffer);
	}
	if ( codec ) {
		if ( codec_initialize )
			codec->finalize();
		delete codec;
	}
	initialize();
};

char* At3Parser::open(const char* filename) {
	
	close();
	
	reader = buffered_reader_open(filename, 65536, 1);
	if ( !reader ) {
		finalize();
		return "At3Parser : open buffered_reader fail";
	}
	buffered_reader_seek(reader, 0);
	uint8_t header_buffer[20];
	if ( buffered_reader_read(reader, header_buffer, 20) != 20 ) {
		finalize();
		return "At3Parser : read AT3 header fail";
	}
	if ( *((uint32_t*)(&header_buffer[0x00])) != 0x46464952 ) { // "RIFF" tag
		finalize();
		return "At3Parser : AT3 header error";
	}
	if ( ( *((uint32_t*)(&header_buffer[0x08])) != 0x45564157 ) || ( *((uint32_t*)(&header_buffer[0x0C])) != 0x20746D66 ) ) { // "WAVEfmt " tag
		finalize();
		return "At3Parser : AT3 header error";
	}
	uint32_t wavefmt_size = *((uint32_t*)(&header_buffer[0x10]));
	uint8_t* wavefmt_buffer = (uint8_t*)malloc(wavefmt_size);
	if ( wavefmt_buffer == 0 ) {
		finalize();
		return "At3Parser : malloc WaveFMT buffer fail";
	}
	if ( buffered_reader_read(reader, wavefmt_buffer, wavefmt_size) != wavefmt_size ) {
		free(wavefmt_buffer);
		finalize();
		return "At3Parser : read WaveFMT header fail";
	}
	
	atrac3_type = *((uint16_t*)(&wavefmt_buffer[0]));
	if ( atrac3_type != 0x270 && atrac3_type != 0xFFFE ) {
		free(wavefmt_buffer);
		finalize();
		return "At3Parser : Atrac3 type error";
	}
	
	init_data.channels = *((uint16_t*)(&wavefmt_buffer[0x02]));
	init_data.samplerate = *((uint32_t*)(&wavefmt_buffer[0x04]));
	init_data.sample_bits = 0x10;
	if ( atrac3_type == 0x270 )
		init_data.samples_per_frame = 1024;
	else
		init_data.samples_per_frame = 2048;
	init_data.samples_per_decoded = init_data.samples_per_frame;
	init_data.frame_align = *((uint16_t*)(&wavefmt_buffer[0x0C]));
	
	if ( atrac3_type == 0xFFFE ) {
		atrac3_plus_flag[0] = wavefmt_buffer[0x2A];
		atrac3_plus_flag[1] = wavefmt_buffer[0x2B];
	}
	free(wavefmt_buffer);
	
	uint32_t data_header[2];
	if ( buffered_reader_read(reader, data_header, 8) != 8 ) {
		finalize();
		return "At3Parser : read data header fail";
	}
	while(data_header[0] != 0x61746164 ) {
		buffered_reader_seek(reader, buffered_reader_position(reader)+data_header[1]);
		if ( buffered_reader_read(reader, data_header, 8) != 8 ) { 
			finalize();
			return "At3Parser : read data header fail";
		}
	}
	
	at3_data_start = buffered_reader_position(reader);
	at3_data_length = data_header[1];	
	
	total_frames = at3_data_length / init_data.frame_align;
	total_samples = total_frames * init_data.samples_per_frame;	
	if ( total_frames == 0 ) {
		finalize();
		return "At3Parser : total_frames = 0";
	}
	frame_index = (AudioFrameIndex*)malloc_64(total_frames * sizeof(AudioFrameIndex));
	if ( frame_index == 0 ) {
		finalize();
		return "At3Parser : malloc seek_table fail";
	}
	uint32_t i;
	frame_index[0].frame_position = at3_data_start;
	frame_index[0].frame_size = init_data.frame_align;
	for( i = 1; i < total_frames; i++ ) {
		frame_index[i].frame_position = frame_index[i-1].frame_position + frame_index[i-1].frame_size;
		frame_index[i].frame_size = init_data.frame_align; 
	}	
	
	output_buffer = malloc_64(init_data.samples_per_frame<<2);
	if ( output_buffer == 0 ) {
		finalize();
		return "At3Parser : malloc output_buffer fail";
	}
	if ( atrac3_type == 0x270 )
		read_buffer = malloc_64(0x180);
	else
		read_buffer = malloc_64(init_data.frame_align + 8);
	if ( read_buffer == 0 ) {
		finalize();
		return "At3Parser : malloc read_buffer fail";
	}
	
	codec = AudioCodec::create_audio_codec(AudioCodec::ATRAC3);
	if ( !codec ) {
		finalize();
		return "At3Parser : create audio codec fail";
	}
	char* result = codec->initialize(&init_data);
	if ( result ) {
		finalize();
		return result;
	}
	codec_initialize = true;
	
	is_open = true;
	return 0;
};

void At3Parser::close() {
	if ( is_open ) {
		finalize();
	}
};
	
uint32_t At3Parser::get_samplerate() {
	return init_data.samplerate;
};

uint32_t At3Parser::get_channels() {
	return init_data.channels;
};

uint64_t At3Parser::get_duration() {
	uint64_t duration = 1000000LL*total_samples/init_data.samplerate;
	return duration;
};
	
uint32_t At3Parser::get_samples_per_frame() {
	return init_data.samples_per_frame;
};

uint32_t At3Parser::get_max_samples_per_frame() {
	return init_data.samples_per_frame;
};

uint64_t At3Parser::seek_time(uint64_t time) {
	uint32_t samples = (uint32_t)(time*init_data.samplerate/1000000LL);
	if ( samples > total_samples )
		samples = total_samples;
	
	uint32_t frame = samples/init_data.samples_per_frame;
	
	if (frame >= total_frames)
		frame = total_frames - 1;
	
	buffered_reader_seek(reader, frame_index[frame].frame_position);
	
	uint64_t current = 1000000LL*frame*init_data.samples_per_frame/init_data.samplerate;
	return current;
};

char* At3Parser::get_frame(void** pcm, uint32_t* samples) {
	
	if ( !is_open )
		return "At3Parser : parser is not open";
	
	uint32_t read_size;
	if ( atrac3_type == 0x270 ) {
		memset(read_buffer, 0, 0x180);
		read_size = buffered_reader_read(reader, read_buffer, init_data.frame_align);
	}
	else {
		memset(read_buffer, 0, 8+init_data.frame_align);
		uint8_t* p = (uint8_t*)read_buffer;
		p[0] = 0x0F;
		p[1] = 0xD0;
		p[2] = atrac3_plus_flag[0];
		p[3] = atrac3_plus_flag[1];
		read_size = buffered_reader_read(reader, (uint8_t*)read_buffer+8, init_data.frame_align);
	}
	if ( read_size != init_data.frame_align ) {
		*pcm = output_buffer;
		*samples = 0;
	}
	else {
		memset(output_buffer, 0, init_data.samples_per_frame << 2);
		int32_t get_samples = codec->decode(read_buffer, (atrac3_type == 0xFFFE ? (read_size+8) : read_size), output_buffer);
		*samples = (get_samples<0) ? 0 : get_samples;
		*pcm = output_buffer;
	}
	
	return 0;
};



